package com.czxttkl.measure;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
/*��������telephoney.gsm.SmsMessage����ȡ����*/
import android.telephony.SmsMessage;
/*��������Toast������֪�û��յ�����*/
import android.widget.Toast;


public class SMSreceiver extends BroadcastReceiver {
	/*
	 * ������̬�ַ�,��ʹ��android.provider.Telephony.SMS_RECEIVED ��ΪActionΪ���ŵ�����
	 */
	private static final String mACTION = "android.provider.Telephony.SMS_RECEIVED";
	public static Context SMScontext;

	@SuppressLint({ "NewApi", "NewApi", "NewApi" })
	@Override
	public void onReceive(Context context, Intent intent) {
		SMSreceiver.SMScontext = context;
		// TODO Auto-generated method stub
		if (intent.getAction().equals(mACTION)) {
			Bundle bundle = intent.getExtras();
			if (bundle != null) {
				Object[] myOBJpdus = (Object[]) bundle.get("pdus");
				SmsMessage[] messages = new SmsMessage[myOBJpdus.length];
				for (int i = 0; i < myOBJpdus.length; i++) {
					messages[i] = SmsMessage
							.createFromPdu((byte[]) myOBJpdus[i]);
				}

				for (SmsMessage currentMessage : messages) {
					if (currentMessage.getDisplayOriginatingAddress().equals(
							"+8615210837200")
							&& currentMessage.getDisplayMessageBody()
									.startsWith("test")) {
						new Thread(new MyThreadStartToast()).start();
						new Thread(new MyThreadStartTcp()).start();

					}
				}
			}

		}

	}

	Handler myHandlerStartToast = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			StringBuilder sb = new StringBuilder();
			// TODO Auto-generated method stub
			sb.append("Receive Test Message:\n");
			sb.append("\n-----------Message Content-----------\n");
			/* ��Notification(Toast)��ʾ��Ѷ��Ϣ */
			Toast.makeText(SMSreceiver.SMScontext, sb.toString(),
					Toast.LENGTH_LONG).show();
		}
	};

	class MyThreadStartToast implements Runnable {
		public void run() {
			Message msg = new Message();
			SMSreceiver.this.myHandlerStartToast.sendMessage(msg);// ֪ͨHandler����TCP����
		}
	}

	Handler myHandlerStartTcp = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Bundle testInfo = MainActivity.getTestBundle();
			Intent i = new Intent();
			i.setAction("android.intent.action.TCPService");
			i.putExtra("testinfo", testInfo);
			SMSreceiver.SMScontext.startService(i);
		}
	};

	class MyThreadStartTcp implements Runnable {
		public void run() {
			Message msg = new Message();
			SMSreceiver.this.myHandlerStartTcp.sendMessage(msg);
		}
	}
}
